import axios from 'axios'

export default {
  namespaced: true, // 开启命名空间
  state: {
    list: [] // 准备存储购物车数据
  },
  mutations: {
    updateList (state, val) {
      state.list = val
    },
    // 修改状态的方法
    updateState (state, id) {
      const row = state.list.find(item => item.id === id)
      row.goods_state = !row.goods_state
    },
    // 修改数量的方法
    updateCount (state, obj) {
      const row = state.list.find(item => item.id === obj.id)
      // if (数量已经是1了 && 又点击了减号) return
      if (row.goods_count === 1 && obj.val === -1) return
      row.goods_count += obj.val
      // console.log(obj)
    },
    // 修改所有的状态
    updateAllState (state, boo) {
      state.list.forEach(item => {
        item.goods_state = boo
      })
    }
  },
  actions: {
    async initData (store) {
      const { data: res } = await axios.get('http://www.itcbc.com:3006/api/cart')
      store.commit('updateList', res.list)
    }
  },
  getters: {
    // 计算是否全部选中
    isFull (state) {
      return state.list.every(item => item.goods_state === true)
    },
    // 计算已选商品的总数量
    total (state) {
      // 先筛选出已选的商品
      const a = state.list.filter(item => item.goods_state === true)
      return a.reduce((t, c) => t + c.goods_count, 0)
    },
    // 计算已选商品的总价格
    amount (state) {
      // 先筛选出已选的商品
      const a = state.list.filter(item => item.goods_state === true)
      return a.reduce((t, c) => t + c.goods_count * c.goods_price, 0)
    }
  }
}
